package com.rth.wx.controller;

import com.rth.wx.Handler.WechatMsgHandler;
import com.rth.wx.Handler.WechatMsgHandlerFactory;
import com.rth.wx.constant.WxConstant;
import com.rth.wx.utils.MessageUtil;
import com.rth.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

@RestController
@Slf4j
public class CallBackController {

    @Resource
    private WechatMsgHandlerFactory wechatMsgHandlerFactory;

    @RequestMapping("/test")
    public String test() {
        return "hello world";
    }

    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr
    ) {
        log.info("get验签请求参数:signature:{},timestamp:{},nonce:{},echost:{}", signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(WxConstant.WX_TOKEN, timestamp, nonce, "");
        if (shaStr.equals(shaStr)) {
            return echostr;
        }

        return "unknown";
    }

    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msgSignature", required = false) String msgSignature
    ) {
        log.info("接收到微信的请求:requestBody:{},signature:{},timestamp:{},nonce:{},msgSignature:{}"
                , requestBody, signature, timestamp, nonce, msgSignature);


        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);

        StringBuilder sb = new StringBuilder();
        sb.append(msgMap.get("MsgType"));

        if (msgMap.get("Event") != null){
            sb.append(".");
            sb.append(msgMap.get("Event")); };
        WechatMsgHandler msgTypeHandler = wechatMsgHandlerFactory.getWechatMsgHandler(sb.toString());
        if (Objects.isNull(msgTypeHandler)){
            return "unknown";
        }
        String result = msgTypeHandler.handlerByMsgType(msgMap);

        return result;
    }
}